from rest_framework.authtoken.models import Token
from django.contrib.auth import authenticate
from django.views.decorators.csrf import csrf_exempt
import json
from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse, HttpResponseBadRequest

# login 登录验证--POST
@csrf_exempt
def login(request):
    if request.method == 'POST':
        # username = request.POST.get('username')
        # password = request.POST.get('password')
        try:
            # 获取请求体的原始数据
            body = request.body.decode('utf-8')
            data = json.loads(body)
        except:
            return JsonResponse({'message': 'request body is required.'}, status=400)
        # 获取用户名和密码
        username = data.get('username')
        password = data.get('password')
        # 验证
        user = authenticate(username=username, password=password)
        if user is not None:
            token, created = Token.objects.get_or_create(user=user)
            return JsonResponse({'token': token.key}, status=200)
        else:
            return JsonResponse({'message': 'Invalid credentials'}, status=400)